use std::io::prelude::*;
use std::net::{Shutdown, TcpStream, TcpListener};
use std::time::Duration;
use std::thread;


fn main() {
    test1();
    // test2();
}

fn test1() {
    let listener = TcpListener::bind("127.0.0.1:2020").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();
        thread::spawn(|| {
            handle_connection(stream);
        });
    }
}

fn handle_connection(mut stream: TcpStream) {
    let max_expected_bytes = 8192;

    let mut buffer = vec![0u8; max_expected_bytes];
    stream.read(&mut buffer);
    println!("rec  {} ", "data");
    // for element in buffer.iter() {
    //     print!("{}  ", element);
    // }
    println!();

    let a: [u8; 2] = [0x05, 0x00];
    stream.write(&a);
    stream.flush();

    let mut buffer2 = vec![0u8; max_expected_bytes];
    stream.read(&mut buffer2);

    let url_length = buffer2.get(4).unwrap();
    let end = (5 + url_length) as usize;
    let domain = buffer2[5..end].to_vec();
    let domain_url = String::from_utf8_lossy(&domain);
    println!("domain_url: {}", domain_url);
    let port1 = buffer2.get(end).unwrap();
    let port2 = buffer2.get(end + 1).unwrap();
    let domain_port = ((*port1 as u16) << 8) + (*port2 as u16);
    println!("domain_port: {}", domain_port);
    let url = format!("{}:{}", domain_url, domain_port);
    println!("url:{}", url);

    let port: u16 = 2020;
    let b1 = (port >> 8) as u8;
    let b2 = (port & 0xff) as u8;
    println!("port: {}", port);

    let ip = 127;
    let a: [u8; 10] = [0x05, 0x00, 0x00, 0x01, 0x7f, 0x00, 0x00, 0x01, b1, b2];
    stream.write(&a);
    stream.flush();
    println!();
    // 流程结束


    let mut buffer4 = vec![0u8; max_expected_bytes];
    stream.read(&mut buffer4);

    let result = TcpStream::connect(url);
    if result.is_err() {
        println!("Couldn't connect to server...");
        return;
    } else {
        println!("Connected to the server!");
    }
    let mut stream_out = result.unwrap();
    stream_out.write(&mut buffer4);
    stream_out.flush();

    println!("{} write success.", "buffer4");

    let mut buffer55 = vec![];
    stream_out.read_to_end(&mut buffer55);
    stream.write(&mut buffer55);
    stream.flush();
    println!("{} write success.", "buffer55");
}


fn test2() {
    let mut stream_out = TcpStream::connect("www.tp-shop.cn:80").unwrap();

    let send = b"GET /Public/images/mycat.png HTTP/1.0\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.1\r\nHost: www.tp-shop.cn\r\n\r\n";

    stream_out.write(send).unwrap();
    stream_out.flush().unwrap();

    let mut buffer3 = vec![];
    stream_out.read_to_end(&mut buffer3).unwrap();
    for element in buffer3.iter() {
        print!(" {}", element);
    }

    println!();

    let content = String::from_utf8_lossy(&buffer3);
    println!("client rec: {}", content);
}




